---
title: "Structures and Unions"
description: "Learn C structures and unions from a JavaScript perspective. Understand struct, union, memory layout, and compare with JavaScript objects."
---

# Structures and Unions

## 1. Introduction

### From JavaScript Objects to C Structures

In JavaScript, objects are dynamic collections of key-value pairs, supporting flexible property addition and deletion. In C, structures (`struct`) provide a way to group related variables under one name, with a fixed memory layout. Unions (`union`) allow different data types to share the same memory location.

> 💡 **Key Concept**: C structures and unions are essential for modeling complex data, memory optimization, and system-level programming.

## 2. Syntax Comparison

<UniversalEditor title="Structs and Objects" compare={true}>
```javascript !! js
// JavaScript - object literal
const person = {
    name: "Alice",
    age: 30,
    isStudent: false
};

// Access and modify properties
console.log(person.name);
person.age = 31;

// Dynamic property addition
person.email = "alice@example.com";

// Nested objects
person.address = { city: "Beijing", zip: "100000" };
```

```c !! c
#include <stdio.h>
#include <string.h>

// Structure definition
typedef struct {
    char name[50];
    int age;
    int isStudent; // 0 = false, 1 = true
} Person;

int main() {
    // Declare and initialize struct
    Person person;
    strcpy(person.name, "Alice");
    person.age = 30;
    person.isStudent = 0;

    // Access and modify members
    printf("Name: %s\n", person.name);
    person.age = 31;

    // No dynamic property addition in C
    // Nested struct
    struct Address {
        char city[50];
        char zip[10];
    } address = {"Beijing", "100000"};

    return 0;
}
```
</UniversalEditor>

## 3. Unions

<UniversalEditor title="Unions" compare={true}>
```javascript !! js
// JavaScript does not have unions, but variables can hold any type
let value = 42;
value = "hello";
value = { x: 1 };
```

```c !! c
#include <stdio.h>
#include <string.h>

// Union definition
union Data {
    int i;
    float f;
    char str[20];
};

int main() {
    union Data data;
    data.i = 10;
    printf("data.i = %d\n", data.i);
    data.f = 220.5;
    printf("data.f = %f\n", data.f);
    strcpy(data.str, "C Language");
    printf("data.str = %s\n", data.str);
    // Only the last written member is valid
    return 0;
}
```
</UniversalEditor>

## 4. Common Pitfalls
- C structs have fixed layout; no dynamic property addition.
- Unions share memory; only one member is valid at a time.
- String handling requires care (use `strcpy`, buffer size checks).
- Memory alignment and padding may affect struct size.

## 5. Exercises
1. Define a struct `Book` with title, author, and price. Write code to input and print book info.
2. Create a union that can store either an `int`, a `float`, or a `char[10]`. Demonstrate usage.
3. Compare memory usage of a struct and a union with the same members.

## 6. Performance Analysis
- Structs provide efficient, cache-friendly data layout.
- Unions save memory when only one member is used at a time.
- Improper use of unions can lead to undefined behavior.

---

> **Summary**: C structures and unions are powerful tools for modeling data and optimizing memory. Unlike JavaScript objects, they have fixed layouts and require explicit memory management. Mastery of these concepts is essential for system programming and performance-critical applications. 